﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Xml;
using System.IO;

namespace LibraryWinService
{
    partial class Notify : ServiceBase
    {
        Timer timer1 = new Timer();
        public Notify()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.
            //ad 1: handle Elapsed event
            timer1.Elapsed += new ElapsedEventHandler(OnElapsedTime);

            //ad 2: set interval to 1 minute (= 60,000 milliseconds)

            timer1.Interval = 60000;

            //ad 3: enabling the timer
            timer1.Enabled = true;
            
            writeLogMessage("\n\nStarting service");
            //timer2_Tick(null, null);
        }

        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
            timer1.Enabled = false;
            writeLogMessage("Ending service");
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
                                 
        }
        private void OnElapsedTime(object sender, EventArgs e)
        {
            try
            {
                FileStream fs = new FileStream("C:\\CS425\\Winter2009\\BrainpowerInc\\KaylaWorkspace\\trunk\\LibraryWinService\\LibraryWinService\\settings.xml", FileMode.Open, FileAccess.Read,
                                   FileShare.ReadWrite);
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(fs);
                fs.Close();

                XmlNodeList nodes = xmlDoc.GetElementsByTagName("settings");
                String ReserveSendTime = "12:00 AM";
                String OverdueSendTime = "12:30 AM";
                String DueSoonSendTime = "1:00 AM";

                foreach (XmlNode node in nodes)
                {
                    XmlNodeList elements = node.ChildNodes;
                    ReserveSendTime = node.SelectSingleNode("timeToNotifyOfReservedBooks").InnerText;
                    OverdueSendTime = node.SelectSingleNode("timeToNotifyOfOverdueBooks").InnerText;
                    DueSoonSendTime = node.SelectSingleNode("timeToNotifyOfBooksDueSoon").InnerText;
                }
                DateTime rtime = DateTime.Parse("12:00 AM"); //default time if time from settings.xml was invalid
                DateTime otime = DateTime.Parse("12:30 AM"); //default time if time from settings.xml was invalid
                DateTime dtime = DateTime.Parse("1:00 AM"); //default time if time from settings.xml was invalid
                try
                {
                    rtime = DateTime.Parse(ReserveSendTime);
                    otime = DateTime.Parse(OverdueSendTime);
                    dtime = DateTime.Parse(DueSoonSendTime);
                }
                catch (Exception)
                {
                    writeLogMessage("A send time was invalid, using default instead");
                }

                DateTime now = System.DateTime.Now;

                if (now.Hour == rtime.Hour && now.Minute == rtime.Minute)
                {
                    SendEmailNotification mailer = new SendEmailNotification();

                    mailer.sendEmailNotificationofReservedBookAvailable();
                    writeLogMessage("processed reserved books");                    
                }
                if (now.Hour == otime.Hour && now.Minute == otime.Minute)
                {
                    SendEmailNotification mailer = new SendEmailNotification();

                    mailer.sendEmailNotificationofBooksOverdue();
                    writeLogMessage("processed overdue books");
                }
                if (now.Hour == dtime.Hour && now.Minute == dtime.Minute)
                {
                    SendEmailNotification mailer = new SendEmailNotification();

                    mailer.sendEmailReminderofBooksDueSoon();
                    writeLogMessage("processed books due soon");
                }
            }
            catch (Exception)
            {
                writeLogMessage("File couldn't be opened or something.");
            }

            //c:\CS425\Winter2009\BrainpowerInc\KaylaWorkspace\trunk\LibraryWinService\LibraryWinService\bin\Debug

        }
        public void writeLogMessage(string msg)
        {
            System.IO.StreamWriter sw = System.IO.File.AppendText("C:\\CS425\\Winter2009\\BrainpowerInc\\KaylaWorkspace\\trunk\\LibraryWinService\\LibraryWinService\\bin\\Debug\\BPIservicelog.txt");
            try
            {
                string logLine = System.String.Format(
                    "{0:G}: {1}.", System.DateTime.Now, msg);
                sw.WriteLine(logLine);
            }
            finally
            {
                sw.Close();
            }
        }
    }
}
